﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Threading;
using System.Web.Mvc;
using System.Web.Security;
using WebMatrix.WebData;
using LynxWiki.Models;

namespace LynxWiki.Filters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
    {
        private static SimpleMembershipInitializer _initializer;
        private static object _initializerLock = new object();
        private static bool _isInitialized;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Ensure ASP.NET Simple Membership is initialized only once per app start
            LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
        }

        private class SimpleMembershipInitializer
        {
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);

                try {
                    using (var context = new UsersContext()) {
                        if (!context.Database.Exists()) {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                    List<string> roles = Roles.GetAllRoles().AsEnumerable<string>().ToList();
                    if (roles != null) {
                        if (!roles.Contains("WikiUser")) {
                            Roles.CreateRole("WikiUser");
                        }
                        if (!roles.Contains("WikiAdmin")) {
                            Roles.CreateRole("WikiAdmin");
                        }
                    }
                    else {
                        Roles.CreateRole("WikiUser");
                        Roles.CreateRole("WikiAdmin");
                    }

                    string adminUser = string.Empty;
                    if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["BootstrapAdminUser"])) {
                        adminUser = (ConfigurationManager.AppSettings["BootstrapAdminUser"]);
                        MembershipUser user = Membership.GetUser(adminUser);
                        if (user != null) {
                            if (user.UserName == adminUser) {
                                List<string> uRoles = Roles.GetRolesForUser(adminUser).AsEnumerable<string>().ToList();
                                if (!uRoles.Contains("WikiAdmin")) {
                                    Roles.AddUserToRole(adminUser, "WikiAdmin");
                                }
                            }
                        }
                    }


                }
                catch (Exception ex) {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        }
    }
}
